<?php

function bc_cj_price_gen( $isbn ) {
	
	// Get Default Options
	$options = get_option('bc_options');
	extract($options);
	
	// Specify a number of pages and the results per page
	$pagenumber=1;
	$howmany=10;
		
	// Start constructing the URL
	$url = "https://product-search.api.cj.com/v2/product-search?";
	
	$cj_params = array (
		'website-id' => $website_id,
		'advertiser-ids' => $advertiser_ids,
		'page-number' => $pagenumber,
		'records-per-page' => $howmany,
		'sort-by' => 'price'
		);
	
	// If the keyword given ($isbn) is an isbn then specify it 
	// otherwise it is a UPC
	if (bc_isbn_test($isbn) == True) {
		// Clean up ISBN
		$isbn = bc_isbn_validator($isbn);
		$cj_params['isbn'] = $isbn;
	}
	else {
		// Convert isbn to a query friendly term
		$isbn = trim(str_replace(' ', '+', $isbn));
		$cj_params["keywords"] = $isbn;
	}
	
	// Construct the url
	foreach ($cj_params as $key => $value) {
		if ($value == '') 
			$url .= '&' . $key;
		elseif ($key == 'website-id')
			$url .= $key . '=' . $value;
		else
			$url .= '&' . $key . '=' . $value;
	}

	// echo $url; 
	
	// Curl request to Commission Junction
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_POST, FAlSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: '.$cj_id));
	$curl_results = curl_exec($ch);
	curl_close($ch);
	$response = simplexml_load_string($curl_results);
	
	// echo $response;
	
	// Variables to cycle through must do this becasue they have a - in them
	$ad_name = 'advertiser-name';
	$ad_id = 'advertiser-id';
	$buy_url = 'buy-url';
	$price = 'price';
	
	$i = 0;
	$adv_list = array();
	$duplicate = '';
	
	$bc_cj_details = array();
	
	// Loop through response data and get
	// Advertiser Name, Price, Url 
	while ($response->products->product[$i]) {
		
		$my_adv = $response->products->product[$i]->$ad_id;
		
		// Only display one link per advertisor
		foreach ($adv_list as $adv) {		
			if ( intval($my_adv) == intval($adv) )
			{
				$duplicate = True;
				break;
			}
		}
		
		if ( $duplicate != True ) {
			$cj_name = $response->products->product[$i]->$ad_name;
			$cj_price = (double)$response->products->product[$i]->$price;
			$cj_url = $response->products->product[$i]->$buy_url;
			$cj_link =  "<a href='" . $cj_url . "' target='_blank'>$" . number_format($cj_price,2) . "</a>";
						
			$bc_cj_details[(string)$cj_name] = $cj_link;
		}
		else {
			$duplicate = '';
		}
		
		$adv_list[$i] = $my_adv;
		$i++;
		
	}

	return $bc_cj_details;	
}

?>